from django.contrib import admin
from django.utils.html import format_html
from .models import *

# 站点设置
admin.site.site_title = '母婴后台系统'
admin.site.site_header = "母婴电商后台管理系统"
admin.site.index_title = "母婴平台管理"


@admin.register(Types)
class TypesAdmin(admin.ModelAdmin):
    list_display = [x for x in list(Types._meta._forward_fields_map.keys())]
    search_fields = ['firsts', 'seconds']
    list_filter = ['firsts']


@admin.register(CommodityInfos)
class CommodityInfosAdmin(admin.ModelAdmin):
    fieldsets = (
        ('商品信息', {
            'fields': ('name', 'sezes', 'types', 'price', 'discount')
        }),
        ('收藏数量', {
            'classes': ('collapse',),
            'fields': ('likes',),
        }),
    )

    ordering = ['id']
    sortable_by = ('price', 'discount')
    list_display = ['id', 'name', 'sezes', 'types', 'price', 'discount', 'colored_name']
    list_filter = ['types']
    list_per_page = 100
    list_max_show_all = 200
    list_editable = ['name']
    search_fields = ['name', 'types']
    save_as = True
    actions_on_top = False
    actions_on_bottom = True

    def colored_name(self, obj):
        return format_html('<span style="color:red">{}</span>', obj.name)

    colored_name.short_description = '商品名称(红色)'
    colored_name.admin_order_field = 'name'

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'types':
            db_field.choices = [(x['seconds'], x['seconds']) for x in Types.objects.values('seconds')]
        return super().formfield_for_dbfield(db_field, **kwargs)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(id__lt=2)

    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == 'types':
            kwargs['choices'] = (('童装', '童装'), ('进口奶粉', '进口奶粉'))
        return super().formfield_for_choice_field(db_field, request, **kwargs)

def save_model(self, request, obj, form, change):
    """
    对数据的修改实现日志记录
    request:当前用户的请求对象
    obj:模型的数据对象
    form:模型表单，是Django自动创建的模型表单
    change:判断当前请求是来自于数据修改页（True）还是数据新增页False
    """
    if change:
        # 获取当前用户名
        user = request.user.username
        # 使用模型获取数据,pk代表有主键属性的字段
        name = self.model.objects.get(pk=obj.pk).name
        # 使用表达获取数据
        types = form.cleaned_data['types']
        # 写入日志文件
        f = open("d://log.txt", 'a', encoding='utf-8')
        f.write(name + "商品类型：" + types + "被" + user + "修改" + '\r\n')
        f.close()
    else:
        pass
    super().save_model(request, obj, form, change)